package app.pumpkin.com.myandroiddemo.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import app.pumpkin.com.myandroiddemo.R;
import app.pumpkin.com.myandroiddemo.receiver.BroadcastActivity;

/**
 * @author wangshy
 */
public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {

    private IMyBinder myBinder;
    private MyConn conn;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        findViewById(R.id.button).setOnClickListener(this);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button) {
            conn = new MyConn();
            intent = new Intent(this, MyService.class);
            bindService(intent, conn, BIND_AUTO_CREATE);
        } else if (v.getId() == R.id.button1) {
            myBinder.invokeMethodInMyService();
        } else {
            unbindService(conn);
        }
    }

    public void receiver(View view) {
        startActivity(new Intent(this, BroadcastActivity.class));
    }

    public void check(View v) {
        intent = new Intent(this, MyService.class);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) { //iBinder为服务里面onBind()方法返回的对象，所以可以强转为IMyBinder类型
            myBinder = (IMyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    }
}
